package com.mydubbo.rpc.netty;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

import com.alibaba.fastjson.JSON;
import com.mydubbo.core.MyDubboServiceStarter;
import com.mydubbo.rpc.dto.Request;
import com.mydubbo.rpc.dto.Response;
import com.mydubbo.util.Log;

public class NettyServerHandler extends SimpleChannelHandler {

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception {
		super.messageReceived(ctx, me);
		Log.log("服务端接收到消息=>" + me.getMessage());
		String text = me.getMessage().toString();
		Request request = JSON.parseObject(text, Request.class);
		String methodName = request.getMethod();
		Class<?> clazz = request.getClazz();
		Object[] args = request.getArgs();
		Class<?>[] parameterTypes = request.getParameterTypes();
		Response response = new Response();
		Object target = MyDubboServiceStarter.getInstance().getBean(clazz.getName());
		
		try {
			Object ret = clazz.getMethod(methodName, parameterTypes).invoke(target, args);
			response.setId(response.getId());
			response.setData(ret);
		} catch (Exception e) {
			e.printStackTrace();
		}
		new NettySender(ctx.getChannel()).sendMessage(JSON.toJSONString(response));
	}
	
}
